#!/usr/bin/env python3
"""
用户管理数据库模型
简化的教师认证系统
"""

import json
import pymysql
from datetime import datetime
from typing import Dict, List, Any, Optional
from dataclasses import dataclass, asdict
from database_config import DatabaseConfig
import hashlib

@dataclass
class User:
    """用户数据模型"""
    id: Optional[int] = None
    username: str = ""
    password_hash: str = ""
    real_name: str = ""
    email: Optional[str] = None
    role: str = "teacher"  # teacher, admin
    is_active: bool = True
    created_at: Optional[datetime] = None
    updated_at: Optional[datetime] = None
    last_login: Optional[datetime] = None

class UserDatabase:
    """用户数据库管理"""
    
    def __init__(self):
        self.config = DatabaseConfig.get_config()
        self.init_database()
    
    def get_connection(self):
        """获取MySQL数据库连接"""
        return pymysql.connect(**self.config)
    
    def init_database(self):
        """初始化用户表"""
        conn = self.get_connection()
        try:
            cursor = conn.cursor()
            
            # 创建用户表
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS users (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    username VARCHAR(50) UNIQUE NOT NULL COMMENT '用户名',
                    password_hash VARCHAR(255) NOT NULL COMMENT '密码哈希',
                    real_name VARCHAR(100) NOT NULL COMMENT '真实姓名',
                    email VARCHAR(100) COMMENT '邮箱',
                    role VARCHAR(20) DEFAULT 'teacher' COMMENT '角色',
                    is_active BOOLEAN DEFAULT TRUE COMMENT '是否激活',
                    created_at DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
                    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
                    last_login DATETIME COMMENT '最后登录时间',
                    INDEX idx_username (username),
                    INDEX idx_role (role)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户表'
            ''')
            
            conn.commit()
            
            # 创建默认管理员账号（如果不存在）
            self.create_default_admin()
            
        except Exception as e:
            conn.rollback()
            raise e
        finally:
            conn.close()
    
    def hash_password(self, password: str) -> str:
        """密码哈希"""
        return hashlib.sha256(password.encode()).hexdigest()
    
    def verify_password(self, password: str, password_hash: str) -> bool:
        """验证密码"""
        return self.hash_password(password) == password_hash
    
    def create_default_admin(self):
        """创建默认管理员账号"""
        conn = self.get_connection()
        try:
            cursor = conn.cursor()
            
            # 检查是否已存在管理员
            cursor.execute("SELECT COUNT(*) FROM users WHERE role = 'admin'")
            admin_count = cursor.fetchone()[0]
            
            if admin_count == 0:
                # 创建默认管理员账号
                admin_password = "admin123"  # 默认密码，建议首次登录后修改
                password_hash = self.hash_password(admin_password)
                
                cursor.execute('''
                    INSERT INTO users (username, password_hash, real_name, role)
                    VALUES (%s, %s, %s, %s)
                ''', ("admin", password_hash, "系统管理员", "admin"))
                
                conn.commit()
                print("默认管理员账号已创建:")
                print("  用户名: admin")
                print("  密码: admin123")
                print("  请首次登录后立即修改密码！")
                
        except Exception as e:
            conn.rollback()
            raise e
        finally:
            conn.close()
    
    def create_user(self, username: str, password: str, real_name: str, email: str = None, role: str = "teacher") -> int:
        """创建用户"""
        conn = self.get_connection()
        try:
            cursor = conn.cursor()
            
            password_hash = self.hash_password(password)
            
            cursor.execute('''
                INSERT INTO users (username, password_hash, real_name, email, role)
                VALUES (%s, %s, %s, %s, %s)
            ''', (username, password_hash, real_name, email, role))
            
            conn.commit()
            return cursor.lastrowid
        except Exception as e:
            conn.rollback()
            raise e
        finally:
            conn.close()
    
    def authenticate_user(self, username: str, password: str) -> Optional[User]:
        """用户认证"""
        conn = self.get_connection()
        try:
            cursor = conn.cursor()
            cursor.execute('''
                SELECT id, username, password_hash, real_name, email, role, 
                       is_active, created_at, updated_at, last_login
                FROM users WHERE username = %s AND is_active = 1
            ''', (username,))
            
            row = cursor.fetchone()
            if row and self.verify_password(password, row[2]):
                # 更新最后登录时间
                cursor.execute('''
                    UPDATE users SET last_login = %s WHERE id = %s
                ''', (datetime.now(), row[0]))
                conn.commit()
                
                return User(
                    id=row[0], username=row[1], password_hash=row[2], real_name=row[3],
                    email=row[4], role=row[5], is_active=row[6], created_at=row[7],
                    updated_at=row[8], last_login=datetime.now()
                )
            return None
        except Exception as e:
            raise e
        finally:
            conn.close()
    
    def get_user_by_id(self, user_id: int) -> Optional[User]:
        """根据ID获取用户"""
        conn = self.get_connection()
        try:
            cursor = conn.cursor()
            cursor.execute('''
                SELECT id, username, password_hash, real_name, email, role,
                       is_active, created_at, updated_at, last_login
                FROM users WHERE id = %s AND is_active = 1
            ''', (user_id,))
            
            row = cursor.fetchone()
            if row:
                return User(
                    id=row[0], username=row[1], password_hash=row[2], real_name=row[3],
                    email=row[4], role=row[5], is_active=row[6], created_at=row[7],
                    updated_at=row[8], last_login=row[9]
                )
            return None
        except Exception as e:
            raise e
        finally:
            conn.close()
    
    def get_all_users(self) -> List[User]:
        """获取所有用户"""
        conn = self.get_connection()
        try:
            cursor = conn.cursor()
            cursor.execute('''
                SELECT id, username, password_hash, real_name, email, role,
                       is_active, created_at, updated_at, last_login
                FROM users WHERE is_active = 1 ORDER BY created_at DESC
            ''')
            
            rows = cursor.fetchall()
            users = []
            for row in rows:
                users.append(User(
                    id=row[0], username=row[1], password_hash=row[2], real_name=row[3],
                    email=row[4], role=row[5], is_active=row[6], created_at=row[7],
                    updated_at=row[8], last_login=row[9]
                ))
            
            return users
        except Exception as e:
            raise e
        finally:
            conn.close()
    
    def update_user_password(self, user_id: int, new_password: str) -> bool:
        """更新用户密码"""
        conn = self.get_connection()
        try:
            cursor = conn.cursor()
            password_hash = self.hash_password(new_password)
            
            cursor.execute('''
                UPDATE users SET password_hash = %s, updated_at = %s WHERE id = %s
            ''', (password_hash, datetime.now(), user_id))
            
            conn.commit()
            return cursor.rowcount > 0
        except Exception as e:
            conn.rollback()
            raise e
        finally:
            conn.close()
    
    def deactivate_user(self, user_id: int) -> bool:
        """停用用户"""
        conn = self.get_connection()
        try:
            cursor = conn.cursor()
            cursor.execute('''
                UPDATE users SET is_active = 0, updated_at = %s WHERE id = %s
            ''', (datetime.now(), user_id))
            
            conn.commit()
            return cursor.rowcount > 0
        except Exception as e:
            conn.rollback()
            raise e
        finally:
            conn.close()

# 创建全局实例
user_db = UserDatabase()
